﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Owin;
using CloudStorageLight.Web.Models;
using CloudStorageLight.Core;
using Microsoft.WindowsAzure.Storage.Table;
using ElCamino.AspNet.Identity.AzureTable.Model;
using ElCamino.AspNet.Identity.AzureTable;
using System.Web.Routing;
using System.Security.Principal;
using CloudStorageLight.Core.Web;
using System.Web.Security;
using System.Text;
using Microsoft.Azure.KeyVault;
using System.Security.Cryptography;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Owin;
using Microsoft.Owin.Security.WsFederation;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Net.FtpClient;

namespace CloudStorageLight.Web.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        private ApplicationUserManager _userManager;

        public AccountController()
        {
        }

        public bool DisableLogin { get { return SystemSettings.Instance.DisableLogin; } }

        public ApplicationUserManager UserManager
        {
            get
            {
                _userManager = _userManager ?? OwinContextExtensions.GetUserManager<ApplicationUserManager>(HttpContext.GetOwinContext());
                return _userManager;
            }
            private set
            {
                _userManager = value;
            }
        }


        //
        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.NotAuthorization);
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }


       //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.Prohibited);
            ApplicationUser user = null;
            ApplicationUserManager uManager = null;
            CloudAccount account = null;
            var domain = BlobService.GetCurrentDomain();
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(model.CloudAccount))
                {
                    account = CloudAccount.Load(SystemSettings.Instance.BlobStorage, model.CloudAccount);
                    if (account != null)
                    {
                        var appCtx = new ApplicationDbContext(account.AccountName);
                        uManager = ApplicationUserManager.Create(new IdentityFactoryOptions<ApplicationUserManager>(), appCtx);
                        domain = model.CloudAccount;
                    }
                    else
                    {
                        this.ModelState.AddModelError("CloudAccount", ViewMessages.MsgNotFoundCloudAccount);
                    }
                }
                else
                {
                    uManager = UserManager;
                    account = CloudAccount.Load(SystemSettings.Instance.BlobStorage, domain);
                }
            }
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(SystemSettings.Instance.AuthMode) || SystemSettings.Instance.AuthMode == "UserPassword")
                {
                    if (!account.IsFtpAuthentication() || string.Equals(account.EMailAddress,model.Email, StringComparison.InvariantCultureIgnoreCase))
                    {
                        user = await uManager.FindAsync(model.Email, model.Password);
                        if (user == null)
                        {
                            ModelState.AddModelError("", ViewMessages.MsgInvalidLoginUserPass);
                        }
                        else if (!user.EmailConfirmed)
                        {
                            ModelState.AddModelError("", ViewMessages.MsgNotYetConfirmEmail);
                        }
                    }
                    else
                    {
                        try
                        {
                            var instance = new FtpClient();
                            instance.Host = account.AuthFtpServer;

                            instance.Credentials = new System.Net.NetworkCredential(model.Email, model.Password);
                            instance.EncryptionMode = FtpEncryptionMode.Explicit;
                            instance.ValidateCertificate += (c, e) => { e.Accept = true; };
                            instance.GetListing("/");
                            var email = model.Email + "@" + account.AuthFtpDomain;
                            user = await uManager.FindByEmailAsync(email);
                            if (user == null)
                            {
                                user = new ApplicationUser() { UserName = email, Email = email };
                                user.EmailConfirmed = true;
                                await uManager.CreateAsync(user);
                            }
                        }
                        catch (FtpCommandException)
                        {
                            ModelState.AddModelError("", ViewMessages.MsgInvalidLoginUserPass);
                        }
                    }
                }
                else
                {
                    throw new InvalidOperationException("AuthMode");
                }
            }

            if (ModelState.IsValid)
            {
                if (account.UseClientTokenForIPCheck && !string.IsNullOrEmpty(model.ClientToken))
                {
                    var clientTokenTicket = ClientToken.Parse(model.ClientToken);
                    if (clientTokenTicket == null || !account.CanAccessIPAddress(clientTokenTicket.InitIPAddress))
                    {
                        if (!account.CanAccessIPAddress(WebUtil.GetIPAddress()))
                        {
                            throw new BlobException(BlobExceptionCode.InvalidIPAddress);
                        }
                        model.ClientToken = null;
                    }
                }
                else
                {
                    if (!account.CanAccessIPAddress(WebUtil.GetIPAddress()))
                    {
                        throw new BlobException(BlobExceptionCode.InvalidIPAddress);
                    }

                }

                var appUser = new AppBlobUser(user, null, account);
                SetEncryptedFileProtectedPassword(account, user.Email, model.Password);

                if (model.AdminRole)
                {

                    if (!appUser.HasAdminRole(account))
                    {
                        ModelState.AddModelError("Email", ViewMessages.MsgDontHaveAdminRole);
                    }
                }

                if (ModelState.IsValid)
                {
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        if (!account.CanAccess(user.Email)) throw new BlobException(BlobExceptionCode.NotAuthorization);
                        returnUrl = DomainRouteUrl("files", new { domain = account.AccountName, id = "/" });
                    }
                    if (!string.IsNullOrEmpty(SystemSettings.Instance.MfaCertFile) && model.AdminRole && appUser.HasAdminRole(account) && !string.IsNullOrEmpty(user.CellPhoneNo))
                    {
                        var ticket = new FormsAuthenticationTicket(model.Email, false, 3);
                        Response.Cookies.Add(new HttpCookie(".MfaAuth", FormsAuthentication.Encrypt(ticket)));

                        var mfaUrl = DomainRouteUrl("account", new { action = "Mfa", domain = account.AccountName, returnUrl = returnUrl, regClientToken = (!string.IsNullOrEmpty(model.ClientToken) || !account.UseClientTokenForIPCheck) });
                        return Redirect(mfaUrl);
                    }
                    else
                    {
                        await SignInAsync(user, model.RememberMe, appUser.HasAdminRole(account) && model.AdminRole, account.AccountName, uManager);
                        if (account.UseClientTokenForIPCheck && string.IsNullOrEmpty(model.ClientToken))
                        {
                            var registClientUrl = DomainRouteUrl("account", new { action = "RegisterClientToken", domain = account.AccountName });
                            return Redirect(registClientUrl);
                        }
                        else
                        {
                            return RedirectToLocal(returnUrl);
                        }
                    }

                }
            }

            // ここで問題が発生した場合はフォームを再表示します
            return View(model);
        }

        public ActionResult RegisterClientToken(string returnUrl)
        {
            if (!Url.IsLocalUrl(returnUrl))
            {
                returnUrl = Url.Action("Index", "Home", null, Request.Url.Scheme);
            }
            ViewBag.ReturnUrl = returnUrl;

            var ctoken = new ClientToken{ ExpireDate= DateTime.MaxValue, IsuueDate = DateTime.UtcNow, InitIPAddress = WebUtil.GetIPAddress(), UserName =User.Identity.Name };
            ViewBag.ClientToken = ctoken.ToToken(); 
            return View();
        }

        private string DomainRouteUrl(string routeName, object routeData)
        {
            if (SystemSettings.Instance.MultiDomain)
            {
                return Url.RouteUrl(routeName, routeData);
            }
            else
            {
                RouteValueDictionary newRouteData = new RouteValueDictionary();
                foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(routeData))
                {
                    if (property.Name.ToLower() == "domain") continue;
                    newRouteData.Add(property.Name, property.GetValue(routeData));
                }
                return Url.RouteUrl(routeName, newRouteData);
            }
        }

        private bool DisableUserAdmin
        {
            get
            {
                var account = BlobService.GetCurrentCloudAccount();
                return account.IsFtpAuthentication() && account.EMailAddress != GetCurrentUserName();  
            }
        }

        //
        // GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.Prohibited);
            
            if (DisableUserAdmin) throw new BlobException(BlobExceptionCode.Prohibited);
            return View();
        }

        [AllowAnonymous]
        [ExcludeFromCodeCoverage]
        public ActionResult Mfa(string returnUrl, bool regClientToken)
        {
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.RegClientToken = regClientToken;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ExcludeFromCodeCoverage]
        public async Task<ActionResult> Mfa(string returnUrl, bool regClientToken, System.Web.Mvc.FormCollection fc)
        {
            var ticketString = Request.Cookies[".MfaAuth"].Value;
            if (string.IsNullOrEmpty(ticketString)) return RedirectToAction("Login");
            var ticket = FormsAuthentication.Decrypt(ticketString);
            if (ticket.Expired) return RedirectToAction("Login");

            var user = await UserManager.FindByEmailAsync(ticket.Name);
            if (user == null || !user.EmailConfirmed) return RedirectToAction("Login");
            if (string.IsNullOrEmpty(user.CellPhoneNo)) return RedirectToAction("Login");
            if (string.IsNullOrEmpty(SystemSettings.Instance.MfaCertFile)) return RedirectToAction("Login");
            var items = user.CellPhoneNo.Split(' ');

            // Add call details from the user database.
            PfAuthParams pfAuthParams = new PfAuthParams();
            pfAuthParams.Username = user.UserName;
            pfAuthParams.Phone = items.Length > 1 ? items[1] : items[0];
            if (items.Length >= 2) pfAuthParams.CountryCode = items[0];
            pfAuthParams.Mode = pf_auth.MODE_STANDARD;

            pfAuthParams.CertFilePath = SystemSettings.Instance.MfaCertFile;

            // Perform phone-based authentication
            int callStatus;
            int errorId;

            if (!pf_auth.pf_authenticate(pfAuthParams, out callStatus, out errorId))
            {
                return RedirectToAction("Login");
            }

            await SignInAsync(user, false, true);

            if (regClientToken)
            {
                return RedirectToLocal(returnUrl);
            }
            else
            {
                return RedirectToAction("RegisterClientToken", new { returnUrl = returnUrl });
            }
        }

        //
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.Prohibited);
            if (DisableUserAdmin) throw new BlobException(BlobExceptionCode.Prohibited);
            var account = BlobService.GetCurrentCloudAccount();
            if (account == null || !account.CanCreateSelfAccount) throw new BlobException(BlobExceptionCode.NotAvailable);
            if (!account.CanAccess(model.Email))
            {
                ModelState.AddModelError("Email", ViewMessages.MsgInvalidMailDomain);
            }
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
                SetEncryptedFileProtectedPassword(account, user.Email, model.Password);
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //await SignInAsync(user, isPersistent: false);
                    //return RedirectToAction("Index", "Home");

                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    await UserManager.SendEmailAsync(user.Id, ViewMessages.MsgConfirmAccount, string.Format(ViewMessages.MsgConfirmAccountMessage, callbackUrl));
                    return View("RegisterConfirmation");

                }
                else
                {
                    AddErrors(result);
                }
            }

            // ここで問題が発生した場合はフォームを再表示します
            return View(model);
        }

        //
        // GET: /Account/ConfirmEmail
        [AllowAnonymous]
        public async Task<ActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null) 
            {
                return View("Error");
            }

            IdentityResult result = await UserManager.ConfirmEmailAsync(userId, code);
            if (result.Succeeded)
            {
                return View("ConfirmEmail");
            }
            else
            {
                AddErrors(result);
                return View();
            }
        }

        //
        // GET: /Account/ForgotPassword
        [AllowAnonymous]
        public ActionResult ForgotPassword()
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.Prohibited);
            return View();
        }

        //
        // POST: /Account/ForgotPassword
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.Prohibited);
            var account = BlobService.GetCurrentCloudAccount();
            var created = account == null ? false: model.Email == account.EMailAddress;
            if (DisableUserAdmin && !created) throw new BlobException(BlobExceptionCode.Prohibited);
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null)
                {
                    ModelState.AddModelError("", ViewMessages.MsgForgotPasswordInvalidUser);
                    return View();
                }

                // アカウント確認とパスワード リセットを有効にする方法の詳細については、http://go.microsoft.com/fwlink/?LinkID=320771 を参照してください
                // このリンクを含む電子メールを送信します
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, ViewMessages.MsgResetPassword,  string.Format(ViewMessages.MsgForgotPasswordMessage,callbackUrl));
                return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // ここで問題が発生した場合はフォームを再表示します
            return View(model);
        }

        //
        // GET: /Account/ForgotPasswordConfirmation
        [AllowAnonymous]
        public ActionResult ForgotPasswordConfirmation()
        {
            return View();
        }
	
        //
        // GET: /Account/ResetPassword
        [AllowAnonymous]
        public ActionResult ResetPassword(string code)
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.Prohibited);
            if (code == null) 
            {
                return View("Error");
            }
            return View();
        }

        //
        // POST: /Account/ResetPassword
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.Prohibited);
            var account = BlobService.GetCurrentCloudAccount();
            var created = account == null ? false : model.Email == account.EMailAddress;
            if (DisableUserAdmin && !created) throw new BlobException(BlobExceptionCode.Prohibited);
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null)
                {
                    ModelState.AddModelError("", ViewMessages.MsgNotFoundUser);
                    return View();
                }
                IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
                if (result.Succeeded)
                {
                    user = await UserManager.FindByIdAsync(user.Id);
                    user.EmailConfirmed = true;
                    SetEncryptedFileProtectedPassword(BlobService.GetCurrentCloudAccount(), user.Email, model.Password);

                    await UserManager.UpdateAsync(user);

                    return RedirectToAction("ResetPasswordConfirmation", "Account");
                }
                else
                {
                    AddErrors(result);
                    return View();
                }
            }

            // ここで問題が発生した場合はフォームを再表示します
            return View(model);
        }

        //
        // GET: /Account/ResetPasswordConfirmation
        [AllowAnonymous]
        public ActionResult ResetPasswordConfirmation()
        {
            return View();
        }


        //
        // GET: /Account/Manage
        public ActionResult Manage(ManageMessageId? message)
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.Prohibited);
            if (DisableUserAdmin) throw new BlobException(BlobExceptionCode.Prohibited);
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? ViewMessages.MsgChangePasswordSuccess
                : message == ManageMessageId.SetPasswordSuccess ? ViewMessages.MsgSetPasswordSuccess
                : message == ManageMessageId.RemoveLoginSuccess ? ViewMessages.MsgRemoveLoginSuccess
                : message == ManageMessageId.Error ? ViewMessages.MsgGeneral
                : "";
            ViewBag.HasLocalPassword = HasPassword();
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Manage(ManageUserViewModel model)
        {
            if (DisableLogin) throw new BlobException(BlobExceptionCode.Prohibited);
            if (DisableUserAdmin) throw new BlobException(BlobExceptionCode.Prohibited);
            bool hasPassword = HasPassword();
            ViewBag.HasLocalPassword = hasPassword;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasPassword)
            {
                if (ModelState.IsValid)
                {
                    IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
                    if (result.Succeeded)
                    {                        
                        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
                        SetEncryptedFileProtectedPassword(BlobService.GetCurrentCloudAccount(), user.Email, model.NewPassword);
                        await UserManager.UpdateAsync(user);
                        await SignInAsync(user, isPersistent: false);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
            else
            {
                // ユーザーにはパスワードがないので、OldPassword フィールドに値がないために発生した検証エラーを削除します
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }

            // ここで問題が発生した場合はフォームを再表示します
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult LogOff()
        {
            if (SystemSettings.Instance.AuthMode == "ADFS")
            {
                IOwinContext owinContext = HttpContext.GetOwinContext();
                IAuthenticationManager authenticationManager = owinContext.Authentication;
                authenticationManager.SignOut(WsFederationAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
            }
            if (SystemSettings.Instance.AuthMode == "AzureAD")
            {
                HttpContext.GetOwinContext().Authentication.SignOut(
                    new AuthenticationProperties (),
                    OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
            }

            if (string.IsNullOrEmpty(SystemSettings.Instance.AuthMode) 
                || SystemSettings.Instance.AuthMode == "UserPassword")
            {
                AuthenticationManager.SignOut();
                var account = BlobService.GetCurrentDomain();

                if (!string.IsNullOrEmpty(account))
                {
                    var url = DomainRouteUrl("account", new { action = "Login", domain = account });

                    return Redirect(url);
                }
                else
                {
                    return Redirect("~/Account/Login");
                }
            }
            return Redirect("Done");
        }

        [AllowAnonymous]
        public ActionResult Done()
        {
            return View();
        }
        ////
        //// GET: /Account/ExternalLoginFailure
        //[AllowAnonymous]
        //public ActionResult ExternalLoginFailure()
        //{
        //    return View();
        //}

            //[ChildActionOnly]
            //public ActionResult RemoveAccountList()
            //{
            //    var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
            //    ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
            //    return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
            //}

        protected override void Dispose(bool disposing)
        {
            if (disposing && UserManager != null)
            {
                UserManager.Dispose();
                UserManager = null;
            }
            base.Dispose(disposing);
        }

        #region ヘルパー
        // 外部ログインの追加時に XSRF の防止に使用します
        private const string XsrfKey = "XsrfId";

        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        private async Task SignInAsync(ApplicationUser user, bool isPersistent, bool adminAuthenticate = false, string cloudAccount = null, ApplicationUserManager userManager=null)
        {
            userManager = userManager ?? UserManager;
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await user.GenerateUserIdentityAsync(userManager);
            if (adminAuthenticate) identity.AddClaim(new Claim("AdminAuthenticate","true"));
            cloudAccount = cloudAccount ?? BlobService.GetCurrentDomain();

            var account = BlobService.GetCloudAccount(cloudAccount);
            double timeout = FormsAuthentication.Timeout.TotalMinutes;
            if (cloudAccount != null)
            {
                identity.AddClaim(new Claim("CloudAccount", cloudAccount));
                timeout = account.AuthTicketTimeout.Value;
            }
            AuthenticationManager.SignIn(new AuthenticationProperties() { IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(timeout), IsPersistent = isPersistent }, identity);
        }

        private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
        }

        private bool HasPassword()
        {
            var user = UserManager.FindById(User.Identity.GetUserId());
            if (user != null)
            {
                return user.PasswordHash != null;
            }
            return false;
        }

        private void SendEmail(string email, string callbackUrl, string subject, string message)
        {
            // 電子メールの送信については、http://go.microsoft.com/fwlink/?LinkID=320771 を参照してください
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
            Error
        }

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [ExcludeFromCodeCoverage]
        private class ChallengeResult : HttpUnauthorizedResult
        {
            public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null)
            {
            }

            public ChallengeResult(string provider, string redirectUri, string userId)
            {
                LoginProvider = provider;
                RedirectUri = redirectUri;
                UserId = userId;
            }

            public string LoginProvider { get; set; }
            public string RedirectUri { get; set; }
            public string UserId { get; set; }

            public override void ExecuteResult(ControllerContext context)
            {
                var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
                if (UserId != null)
                {
                    properties.Dictionary[XsrfKey] = UserId;
                }
                context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
            }
        }
        #endregion


        [AllowAnonymous]
        public ActionResult CreateCloudAccount()
        {
            if (!SystemSettings.Instance.CanCreateCloudAccountOnline) throw new BlobException(BlobExceptionCode.NotAuthorization);
            var vm = new CloudAccountVM();
            vm.CloudAccount = BlobService.GetCurrentDomain();
            ViewData["MenuVisibility"] = false;
            return View(vm);
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> CreateCloudAccount(CloudAccountVM vm)
        {
            if (!SystemSettings.Instance.CanCreateCloudAccountOnline) throw new BlobException(BlobExceptionCode.NotAuthorization);
            var currentDomain = BlobService.GetCurrentDomain();
            if (SystemSettings.Instance.MultiDomain) 
            {
                if (string.IsNullOrEmpty(vm.CloudAccount))
                {
                    this.ModelState.AddModelError("CloudAccount", ViewMessages.MsgPleaseInputCloudAccount);
                }
                else
                {
                    vm.CloudAccount = vm.CloudAccount.Trim();

                    if (vm.CloudAccount.Length < 5 || vm.CloudAccount.Length > 32 || !System.Text.RegularExpressions.Regex.IsMatch(vm.CloudAccount, "^[a-z][a-z0-9]*$"))
                    {
                        this.ModelState.AddModelError("CloudAccount", ViewMessages.MsgPleaseInputCloudAccountAlphaNumber15);
                    }
                    vm.CloudAccount = vm.CloudAccount.ToLower();
                }

            }
            else
            {
                vm.CloudAccount = "";
            }

            if (this.ModelState.IsValid)
            {
                var account = CloudAccount.Load(SystemSettings.Instance.BlobStorage, vm.CloudAccount);
                if (account != null)
                {
                    this.ModelState.AddModelError("CloudAccount", ViewMessages.MsgAlreadyExists);
                    this.ModelState.AddModelError("", ViewMessages.MsgAlreadyExistsCloudAccount);
                }
            }


            if (this.ModelState.IsValid)
            {
                if (BlobService.GetCurrentDomain() != vm.CloudAccount)
                {
                    return RedirectToAction("CreateCloudAccount", "Account", new { domain = vm.CloudAccount });
                }


                var appuser = new ApplicationUser() { UserName = vm.EMailAddress, Email = vm.EMailAddress };
                var user = new AppBlobUser(appuser, null);
                if (string.IsNullOrEmpty(user.GetDomain()))
                {
                    throw new BlobException(BlobExceptionCode.NotAuthorization);
                }

                await ApplicationUserManager.CreateCloudAccountAsync(vm.CloudAccount);
                var appCtx = new ApplicationDbContext(vm.CloudAccount);

                var uManager = UserManager;// ApplicationUserManager.Create(new IdentityFactoryOptions<ApplicationUserManager>() { }, appCtx);
                
                IdentityResult result = await uManager.CreateAsync(appuser, vm.Password);

                if (result.Succeeded)
                {
                    var cloudAccount = new CloudAccount(vm.CloudAccount)
                    {
                        AccountType = "Web",
                        MailDomain = user.GetDomain(),
                        EMailAddress = user.Name,
                        StorageLimitSize = SystemSettings.Instance.DefaultStorageLimitSize,
                    };
                    cloudAccount.Save(SystemSettings.Instance.BlobStorage);

                    string code = await uManager.GenerateEmailConfirmationTokenAsync(appuser.Id);
                    if (SystemSettings.Instance.MultiDomain)
                    {
                        var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = appuser.Id, code = code }, protocol: Request.Url.Scheme);
                        await uManager.SendEmailAsync(appuser.Id, ViewMessages.MsgConfirmAccount, string.Format(ViewMessages.MsgConfirmAccountMessage, callbackUrl));

                        var queryString = new RouteValueDictionary();
                        foreach (var item in this.Request.QueryString.AllKeys)
                        {
                            queryString.Add(item ?? "", this.Request[item]);
                        }
                        queryString["domain"] = vm.CloudAccount;
                        queryString["Created"] = "1";
                        return View("RegisterConfirmation");
                    }
                    else
                    {
                        uManager.ConfirmEmail(appuser.Id, code);
                        double timeout = FormsAuthentication.Timeout.TotalMinutes;
                        var identity = await appuser.GenerateUserIdentityAsync(uManager);
                        identity.AddClaim(new Claim("AdminAuthenticate", "true"));
                        AuthenticationManager.SignIn(new AuthenticationProperties() { IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(timeout), IsPersistent = false }, identity);
                        return RedirectToAction("CloudSettings", "Settings");

                    }
                }
                else
                {
                    AddErrors(result);
                }
            }
            ViewData["MenuVisibility"] = false;
            return View(vm);
        }

        public ActionResult Wellcome()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult IsAuthenticated()
        {
            return Json(HttpContext.User.Identity.IsAuthenticated, JsonRequestBehavior.AllowGet);
        }

        [AllowAnonymous]
        public ActionResult GetCloudAccount()
        {
            if (!HttpContext.User.Identity.IsAuthenticated) return Json(null);
            var account = BlobService.GetCurrentCloudAccount();
            if (account == null) return null;
            return Json(new { Account = account.AccountName, account.AccountType, account.EMailAddress, account.SpHostUrl }, JsonRequestBehavior.AllowGet);
        }

        protected BlobUser GetCurrentUser()
        {
            return BasicAuthenticateUtil.GetCurrentUser();
        }

        protected string GetCurrentUserName()
        {
            return System.Web.HttpContext.Current.User.Identity.Name;
        }

        public ApplicationDbContext IdentityContent
        {
            get
            {
                return _identityContent ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();
            }
            private set
            {
                _identityContent = value;
            }
        }
        private ApplicationDbContext _identityContent;



        /// <summary>
        /// ユーザリストの表示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> UserList(string query, int maxSize=200)
        {
            var u = GetCurrentUser();
            if (!u.IsAdmin) throw new BlobException(BlobExceptionCode.NotAuthorization);

            var currentUser = await FindByNameAsync(GetCurrentUserName());

            var domain = AppBlobUser.GetDomain(currentUser.UserName) ?? "";
            var vm = new UsersVM();
            vm.Query = query;
            vm.Current = currentUser;
            vm.Users = new List<ApplicationUser>();
            IEnumerable<string> users = IdentityContent.GetUsers(query);
            //if (SystemSettings.Instance.MultiDomain) users = users.Where(x => x.EndsWith(domain, StringComparison.InvariantCultureIgnoreCase));
            foreach (var email in users.Take(maxSize))
            {
                var user = await FindByNameAsync(email);
                if (user.EmailConfirmed == false && user.Timestamp < DateTime.Today.AddDays(-30))
                {
                    await UserManager.DeleteAsync(user);
                    continue;
                }
                vm.Users.Add(user);
            }
            vm.Groups = IdentityContent.GetGroups(); //vm.Users.SelectMany(x => x.Groups).OrderBy(x=>x).Distinct().ToList();
            if (users.Count() > maxSize)
            {
                vm.Message = ViewMessages.MsgFoundOver;
            }
            return View(vm);
        }


        private async Task<ApplicationUser> FindByNameAsync(string email)
        {
            var user = await UserManager.FindByNameAsync(email);
            if (user != null) await user.EnsureRolesAsync(UserManager);
            return user;
        }

        /// <summary>
        /// ユーザ情報の取得
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public async Task<ActionResult> GetUser(string username)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (!CanAccessUser(currentUser, username)) throw new BlobException(BlobExceptionCode.NotAuthorization);
                if (!currentUser.IsAdmin) throw new BlobException(BlobExceptionCode.NotAuthorization);

                var user = await FindByNameAsync(username);
                return PartialView("_BlobUser", user);
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// ユーザ情報の追加
        /// </summary>
        /// <param name="username"></param>
        /// <param name="userpassword"></param>
        /// <param name="confirmuserpassword"></param>
        /// <returns></returns>
        public async Task<ActionResult> AddUser(string username, string userpassword, string confirmuserpassword)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (!CanAccessUser(currentUser, username)) throw new BlobException(ViewMessages.MsgCannotOtherDomain);
                if (!currentUser.IsAdmin) throw new BlobException(BlobExceptionCode.NotAuthorization);

                var user = await FindByNameAsync(username);
                if (user != null) throw new BlobException(BlobExceptionCode.ExistsUser);
                if (userpassword != confirmuserpassword)
                {
                    throw new BlobException(ViewMessages.MsgDiffPassword);
                }

                user = new ApplicationUser() { UserName = username, Email = username, EmailConfirmed = true };

                var account = BlobService.GetCurrentCloudAccount();
                SetEncryptedFileProtectedPassword(BlobService.GetCurrentCloudAccount(), user.Email, userpassword);
                IdentityResult result = await UserManager.CreateAsync(user, userpassword);
                if (!result.Succeeded) return Content(result.Errors.First());
                return Content("");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// ユーザ情報の削除
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task<ActionResult> DeleteUser(string username)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (!CanAccessUser(currentUser, username)) throw new BlobException(ViewMessages.MsgCannotOtherDomain);
                if (!currentUser.IsAdmin) throw new BlobException(BlobExceptionCode.NotAuthorization);

                var user = await FindByNameAsync(username);
                if (user == null) throw new BlobException(BlobExceptionCode.NotFoundUser);
                await UserManager.DeleteAsync(user);
                return Content("");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// ユーザ情報の更新
        /// </summary>
        /// <param name="name"></param>
        /// <param name="roles"></param>
        /// <param name="isAdmin"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> UpdateUser(string username, string roles, string cellPhoneNo)
        {
            try
            {
                //TODO:携帯番号チェック
                var currentUser = GetCurrentUser();
                if (!CanAccessUser(currentUser, username)) throw new BlobException(ViewMessages.MsgCannotOtherDomain);
                if (!currentUser.IsAdmin) throw new BlobException(BlobExceptionCode.NotAuthorization);

                var user = await FindByNameAsync(username);
                if (user == null) throw new BlobException(BlobExceptionCode.NotFoundUser);

                //user.CellPhoneNo = cellPhoneNo;
                //await UserManager.UpdateAsync(user);

                var rolesItem = roles.Split(',').Where(x => !string.IsNullOrEmpty(x));
                var groups = IdentityContent.GetGroups();
                foreach (var role in rolesItem)
                {
                    if (!user.Groups.Contains(role))
                    {
                        if (!groups.Contains(role)) IdentityContent.AddGroups(role);
                        await UserManager.AddToRoleAsync(user.Id, role);
                    }
                }
                foreach (var role in user.Groups)
                {
                    if (!rolesItem.Contains(role))
                    {
                        await UserManager.RemoveFromRoleAsync(user.Id, role);
                    }
                }
                return Content("");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }


        /// <summary>
        /// ユーザ情報の更新
        /// </summary>
        /// <param name="name"></param>
        /// <param name="roles"></param>
        /// <param name="isAdmin"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> ResetUserPassword(string resetUsername, string resetUserpassword, string resetConfirmuserpassword)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (!CanAccessUser(currentUser, resetUsername)) throw new BlobException(ViewMessages.MsgCannotOtherDomain);
                if (!currentUser.IsAdmin) throw new BlobException(BlobExceptionCode.NotAuthorization);

                if (resetUserpassword != resetConfirmuserpassword)
                {
                    throw new BlobException(ViewMessages.MsgDiffPassword);
                }
                var user = await FindByNameAsync(resetUsername);
                if (user == null) throw new BlobException(BlobExceptionCode.NotFoundUser);

                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, code, resetUserpassword);
                if (result.Succeeded)
                {
                    user = await FindByNameAsync(resetUsername);
                    SetEncryptedFileProtectedPassword(BlobService.GetCurrentCloudAccount(), user.Email, resetUserpassword);
                    user.EmailConfirmed = true;
                    await UserManager.UpdateAsync(user);
                    return Content("");
                }
                else
                {
                    return Content(result.Errors.FirstOrDefault() ?? "");
                }

            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }


        private bool CanAccessUser(BlobUser currentUser, string targetUser)
        {
            //ユーザデータベースを分離したためアクセス可能に
            return true;
            //return AppBlobUser.GetDomain(currentUser.Name) == AppBlobUser.GetDomain(targetUser);
        }

        private void SetEncryptedFileProtectedPassword(CloudAccount account, string userName, string password)
        {
            if (account.CanUseUserPasswordProtect || account.IsFtpAuthentication())
            {

                var info = UserInfo.Get(SystemSettings.Instance.BlobStorage, account.AccountName, userName);
                if (info == null)
                {
                    info = new UserInfo(userName);
                }
                var encryptedPass = CryptUtil.EncryptStringAES(password, SystemSettings.Instance.GeneralEncryptKey);
                info.EncryptedFileProtectedPassword = encryptedPass;
                info.Save(SystemSettings.Instance.BlobStorage, account.AccountName);
            }
        }

    }
}